import { getPool } from '../database/db.js';
import { log } from '../utils/logger.js';

export class AccessLog {
  /**
   * 创建访问日志
   */
  static async create(userId, ipAddress, action, details = null, userAgent = null) {
    const pool = getPool();
    try {
      await pool.execute(
        'INSERT INTO access_logs (user_id, ip_address, action, details, user_agent) VALUES (?, ?, ?, ?, ?)',
        [userId, ipAddress, action, details, userAgent]
      );
      return true;
    } catch (error) {
      log.error('创建访问日志失败', { error: error.message });
      // 不抛出错误，避免影响主流程
      return false;
    }
  }

  /**
   * 获取用户的访问日志
   */
  static async getByUser(userId, limit = 100) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        'SELECT * FROM access_logs WHERE user_id = ? ORDER BY created_at DESC LIMIT ?',
        [userId, limit]
      );
      return rows;
    } catch (error) {
      log.error('获取访问日志失败', { error: error.message, userId });
      throw error;
    }
  }

  /**
   * 根据IP获取访问日志
   */
  static async getByIP(ipAddress, limit = 100) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        'SELECT * FROM access_logs WHERE ip_address = ? ORDER BY created_at DESC LIMIT ?',
        [ipAddress, limit]
      );
      return rows;
    } catch (error) {
      log.error('获取IP访问日志失败', { error: error.message, ipAddress });
      throw error;
    }
  }

  /**
   * 获取所有访问日志
   */
  static async getAll(limit = 100) {
    const pool = getPool();
    try {
      const [rows] = await pool.execute(
        'SELECT * FROM access_logs ORDER BY created_at DESC LIMIT ?',
        [limit]
      );
      return rows;
    } catch (error) {
      log.error('获取所有访问日志失败', { error: error.message });
      throw error;
    }
  }

  /**
   * 清理旧日志（保留最近N天）
   */
  static async cleanup(days = 30) {
    const pool = getPool();
    try {
      const [result] = await pool.execute(
        'DELETE FROM access_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)',
        [days]
      );
      
      if (result.affectedRows > 0) {
        log.system(`清理访问日志`, { days, count: result.affectedRows });
      }
      
      return result.affectedRows;
    } catch (error) {
      log.error('清理访问日志失败', { error: error.message });
      throw error;
    }
  }
}

// 定期清理旧日志（每天执行一次，保留30天）
setInterval(() => {
  AccessLog.cleanup(30);
}, 24 * 60 * 60 * 1000);
